package ink.ykb.redissondemo.controller;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import ink.ykb.redissondemo.config.ResponseMsg;
import ink.ykb.redissondemo.config.lock.AquiredLockWorker;
import ink.ykb.redissondemo.config.lock.RedisLock;
import ink.ykb.redissondemo.config.lock.RedisLocker;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/")
public class TestController {
	
	@Autowired
	private RedisLocker redisLocker;
	
	@GetMapping("/test1")
	public String test1(String key) {
		String s = redisLocker.tryLock(key, new AquiredLockWorker<String>() {

			@Override
			public String invokeAfterLockAquire() {
				try {
					int random = (int)Math.floor(Math.random()*5); 
					log.info("sleep:"+random);
					Thread.sleep(random * 1000);
				} catch (InterruptedException e) {
				}
				return "success";
			}
			
			
		},100);
		
		return s;
	}
	
	@GetMapping("/test2")
	public String test2(String key) {
		 redisLocker.tryLock(key, 100);
		return "success";
	}
	
	@GetMapping("/test3")
	public String test3(String key) {
		redisLocker.lock(key);
		return "success";
	}
	
	@GetMapping("/test4")
	public String test4(String key) {
		redisLocker.unLock(key);
		return "success";
	}
	
	
	
	public static int num1 = 0;
	public static AtomicInteger totalNum = new AtomicInteger(0);
	public static AtomicInteger errorNum = new AtomicInteger(0);
	public static AtomicInteger successNum = new AtomicInteger(0);
	
	@RedisLock(prefix = "test5:",key = "t")
	@RequestMapping("/test5")
	public ResponseMsg<Integer> test5(String t) {
		num1++;
		log.info("num1：{}，errorNum：{}，successNum：{}，totalNum：{}",
				num1,errorNum.get(),successNum.get(),totalNum.get());
		int random = (int)Math.floor(Math.random()*10); 
//		try {
//			Thread.sleep(300);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		if(random == 9) {
			throw new RuntimeException("假装报错~~~");
		}
		
		return new ResponseMsg<>(num1);
	}
	
	
}
